<template>
  <div class="moduleManagement h100">
    <div class="PageContent">
        <el-col :span="4" class="left-tree">
          <el-tree :data="treeData" ref="moduleManagementtree"
                   v-if="treeData"
                   :props="defaultProps"
                   node-key="id"
                   default-expand-all
                   check-strictly
                   highlight-current
                   @node-click="handleClick"
          ></el-tree>
        </el-col>
        <el-col :span="20"  class="right-tree">
          <el-row style="text-align: left;line-height: 5em;">
            <el-button  v-if="btnRight.btnModuleManagementRefresh" type="primary">刷新</el-button>
            <el-button  v-if="btnRight.btnModuleManagementAdd" type="primary" @click="add()">添加</el-button>
            <el-button  v-if="btnRight.btnModuleManagementEdit" type="primary" @click="modify()">修改</el-button>
            <el-button  v-if="btnRight.btnModuleManagementDelete" type="danger"  @click="remove()">删除</el-button>
          </el-row>
          <el-table
            ref="moduleManagementTable"
            :data="tableData" :header-cell-style="{background:'rgb(222,225,230)',color:'#606266'}"
            row-key="id"
            border
            default-expand-all
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @row-click="handleRowClick"
            @select="select" @select-all="selectAll"
            style="width: 100%;height: calc(100% - 80px);overflow-y: scroll">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              property="menuName"
              label="菜单名称"
              align = 'center'>
            </el-table-column>
            <el-table-column
              property="menuRoute"
              label="菜单路由地址"
              align = 'center'
              width="200">
            </el-table-column>
            <el-table-column
              property="menuRedirectRoute"
              label="菜单重定向路由"
              align = 'center'
              width="200">
            </el-table-column>
            <el-table-column
              property="menuIcon"
              align = 'center'
              label="图标"
              width="150">
              <template slot-scope="{row,$index}">
                <img v-if="row.menuIcon" :src="require(`../../../static/images/menus/${row.menuIcon}.jpg`)" width="20" height="20" alt="">
              </template>
            </el-table-column>
            <el-table-column
              property="disableState"
              align = 'center'
              label="状态"
              width="150">
              <template slot-scope="{row,$index}">
                <span v-if="row.disableState==0">有效可用</span>
                <span v-else-if="row.disableState==1">无效禁用</span>
              </template>
            </el-table-column>
            <el-table-column
              property="sort"
              align = 'center'
              label="顺序"
              width="150">
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px">
          </div>
        </el-col>
    </div>
    <el-dialog title="菜单模块信息维护" :visible.sync="dialogVisible" width="700px" v-dialogDrag   border >
      <el-form :model="saveData.menu" class="saveform" :rules="rules" ref="moduledialog" :inline="true" label-width="130px" :disabled="saveFlag">
        <el-row :gutter="5">
          <el-form-item label="业务系统:">
            <el-input v-model="saveData.menu.businessSystemName" style="width:515px;" disabled></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="父菜单:" prop="parentId">
            <el-select v-model="saveData.menu.parentId" style="width:515px;" placeholder="请选择" >
              <el-option
                v-for="item in saveData.menus"
                :key="item.id"
                :label="item.menuName"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="菜单显示名称:" prop="menuName">
            <el-input v-model="saveData.menu.menuName" style="width:515px;"  maxlength="50"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="菜单路由地址:" prop="menuRoute">
            <el-input v-model="saveData.menu.menuRoute"  style="width:515px;" maxlength="50"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="菜单重定向路由:" >
            <el-input v-model="saveData.menu.menuRedirectRoute"  style="width:515px;" maxlength="50"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="图标:" prop="menuIcon" >
            <img v-if="saveData.menu.menuIcon" :src="require(`../../../static/images/menus/${saveData.menu.menuIcon}.jpg`)" width="20" height="20" alt="">
            <!--<span v-if="saveData.menu.menuIcon">{{saveData.menu.menuIcon}}</span>-->
            <el-button  v-model="saveData.menu.address" type="primary" v-if="btnRight.btnModuleManagementSelectImg" @click="icondialogVisible = !icondialogVisible" >图标选取</el-button>
          </el-form-item>
          <el-form-item>

          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="状态:" prop="disableState">
            <el-select v-model="saveData.menu.disableState" onkeydown="return (event.keyCode!=8)" style="width:515px;" placeholder="请选择" >
              <el-option
                v-for="item in disableState"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="排序:">
            <el-input onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"  v-model="saveData.menu.sort"  :maxlength="11" style="width:515px;" diabled></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5" class="saveform" >
          <el-form-item label="备注:" >
            <el-input type="textarea"  style="width:515px;" v-model="saveData.menu.remark"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary"  v-if="btnRight.btnModuleManagementSave" @click="Save()" :disabled="saveFlag">保存</el-button>
        <el-button    v-if="btnRight.btnModuleManagementCancel"  @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="图标选择" :visible.sync="icondialogVisible" width="700px" v-dialogDrag   border >
      <div class="wrapper">
        <el-radio-group v-model="iconselect" >
          <el-radio  class="icon"  v-for="(n,index) in iconList" :label="n" style="margin:0 50px 50px 0;">
            <img :src="require(`../../../static/images/menus/${n}.jpg`)" style="vertical-align: middle;" width="50" height="50"/>
          </el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary"  v-if="btnRight.btnModuleManagementSelectImg" @click="iconSelect()">保存</el-button>
        <el-button  v-if="btnRight.btnModuleManagementCancelImg" @click="icondialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as API from '@/api/stystemManagement'
  import {treeTransformate} from "../../utils/treeTransformate";
  var checkicon = (rule, value, callback) => {
    if (!value) {
      return callback(new Error('图标不能为空'));
    }
  };
  export default {
    name: "moduleManagement",
    props: {
      //自定义模板清除属性
      clearable: {
        type: Boolean,
        default: true,
      },
    },
    data(){
      return{
        rules: {
          menuName: [{required: true, message: '请输入菜单显示名称', trigger: 'blur'}],
          menuRoute: [{required: true, message: '请输入菜单路由地址', trigger: 'blur'}],
          // menuRedirectRoute: [{required: true, message: '请输入菜单重定向路由', trigger: 'blur'}],
          parentId:[{required: true, message: '请选择父菜单', trigger: 'blur'}],
          menuIcon: [{required: true, message: '请选择图标', trigger: 'change' }],
          disableState: [{required: true, message: '请选择禁用状态', trigger: 'change'}],
        },
        treeData: [{
          id: 0,
          label: '殡葬业务平台',
          children: []
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        tableData: [],
        goodsServiceList:[],//所有的物品服务包
        currentRow: null,
        tableSelection:[],
        multipleSelection:[],
        saveFlag:false, //保存标志
        onpresscTime:0,  //  阻止短时间内连续点击
        dialogVisible:false,//项目分类维护对话框
        disableState:[
          {label:"有效可用",value:0},{label:"无效禁用",value:1},
        ],
        saveData:{       //保存服务物品类型基本信息
          "menu": {
            // "id": 0,
            "businessSystemId": "",
            "businessSystemName":"",  //界面中增加系统显示用，不传后台
            "parentId": "",
            "menuName": "",
            "menuRoute": "",
            "menuRedirectRoute": "",
            "menuIcon": "",
            "disableState": 0,
            "remark": "",
            "sort": "",
            "version": ""
          },
          "menus": []
        },
        iconList:[
          "tree",
          "table",
          "link",
          "list",
          "user",
          "form",
        ],
        icondialogVisible:false,
        iconselect:"",//选中的icon
        btnRight: {
          btnModuleManagementAdd: true, //添加
          btnModuleManagementEdit: true,//修改
          btnModuleManagementDelete: true,//删除
          btnModuleManagementSave: true,//保存
          btnModuleManagementCancel: true,//取消
          btnModuleManagementRefresh: true,//刷新
          btnModuleManagementSelectImg: true,//图标选取
          btnModuleManagementSaveImg: true,//图标保存
          btnModuleManagementCancelImg: true,//图标取消
        }
      }
    },
    mounted(){
      this.loadBusinessSystemListData()
      //载入按钮
      this.btnRight = this.$route.meta.buttons;
      //遍历属性赋值将true与false字符串转换成布尔型的值
      for (let key of Object.keys(this.btnRight)) {
        this.btnRight[key]=(this.btnRight[key]|| this.btnRight[key]=="true")?true:false;
      }
    },
    methods: {
      //tree单选
      handleClick(data,checked, node){
        if(checked && data.label!="业务模块"){
          this.$refs.moduleManagementtree.setCheckedNodes([data]);
          this.loadSystemMenuListWithBusinessSystemIdData(data.id)
        }
      },
      //点击行触发，选中或不选中复选框`
      handleRowClick(row, column, event) {
        if (this.tableSelection.length>0){
          this.$refs.moduleManagementTable.toggleRowSelection(this.tableSelection[0],false);
        }
        this.$refs.moduleManagementTable.toggleRowSelection(row);
        this.tableSelection = [row]
      },
      select(selection, row) {
        // 选择项大于1时
        if (selection.length > 1) {
          let del_row = selection.shift();
          // console.log('把数组的第一个元素从其中删除后', selection);
          this.$refs.moduleManagementTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        }
        this.tableSelection = selection
      },
      selectAll(selection) {
        if (selection.length >1) {
          selection.length = 1;
        }
        this.tableSelection = selection
      },
      /*刷新*/
      refresh(){
        let data = this.$refs.moduleManagementtree.getCheckedNodes()
        if (data.length){
          this.loadSystemMenuListWithBusinessSystemIdData(data[0].id)
        }
      },
      //table中类型添加
      add(){
        let data = this.$refs.moduleManagementtree.getCheckedNodes()
        if (!data.length || (data[0].label == "殡葬业务平台" && data[0].id == 0)) {
          this.$message("请选择系统")
          return
        }
        let tabledata = this.tableSelection
        //添加子系统的主菜单
        if (data.length == 0){
          this.$message("未选中业务系统")
          return
        }
        //根据业务系统菜单id加载数据以及所有的菜单
        if(data.length) {
          let code={id:0,businessSystemId:data[0].id}
          this.loadSystemMenuWithIdData(code).then( res => {
            if (res) {
              if (res.menus && res.menus.length) {
                this.saveData.menus=[{
                  "id": 0,
                  "parentId": data[0].parentId,
                  "menuName": data[0].label,
                }]
                res.menus.forEach(item=>{
                  this.saveData.menus.push(item)
                })
              }
              this.saveData.menu = {
                "id": 0,
                "parentId": "",
                "menuName": "",
                "businessSystemId": data[0].id,
                "businessSystemName":data[0].label,  //界面中增加系统显示用，不传后台
                "menuRoute": "",
                "menuRedirectRoute": "",
                "menuIcon": "",
                "disableState": 0,
                "remark": "",
                "sort": "",
                "version": ""
              }

              this.dialogVisible = true
            }
            else{
              this.$message("数据加载失败")
            }

          })
        }
      },
      modify(){
        let data1 = this.$refs.moduleManagementtree.getCheckedNodes()
        if (!data1.length || (data1[0].label == "殡葬业务平台" && data1[0].id == 0)) {
          this.$message("请选择系统")
          return
        }
        let data = this.$refs.moduleManagementTable.selection
        if (data && data.length){
          this.loadSystemMenuWithIdData(data[0]).then( res => {
            if (res) {
              if (res.menus && res.menus.length) {
                this.saveData.menus=[{
                  "id": 0,
                  "parentId": data[0].parentId,
                  "menuName": data[0].label,
                }]
                res.menus.forEach(item=>{
                  this.saveData.menus.push(item)
                })
              }
              if (res.menu) {
                this.saveData.menu = res.menu;
              } else {
                this.saveData.menu = {
                  "id": 0,
                  "businessSystemId": 0,
                }
              }
              let ststem = this.$refs.moduleManagementtree.getCheckedNodes();
              this.saveData.menu.businessSystemId = ststem[0].id;
              this.saveData.menu.businessSystemName = ststem[0].label
              this.dialogVisible = true
            }
            else{
              this.$message("数据加载失败")
            }
            this.dialogVisible = true
          })
        } else{
          this.$message("请选择菜单")
        }
      },
      //table中服务物品类型删除
      remove(){
        let ststem = this.$refs.moduleManagementtree.getCheckedNodes();
        let data = this.tableSelection
        if (ststem.length == 0 || data.length == 0) {
          this.$message("未选中菜单")
          return
        }
        this.$confirm('删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData = []
          data.forEach(item => {
            postData.push({
              "id": item.id,
              "version": item.version
            })
          })
          API['deleteSystemMenuWithId'](postData).then(response => {
            const {message} = response;
            this.$message(message)
            this.loadSystemMenuListWithBusinessSystemIdData(ststem[0].id)
          }).catch(error => {
            this.$message(error)
          })
          }).catch(() => {
          //几点取消的提示
        });
      },

      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //加载系统列表
      loadBusinessSystemListData(){
        API['loadBusinessSystemList']().then(response=>{
          const { data }=response;
          if (!data) {
            this.$message('数据读取失败')
            return
          }
          if (data && data.length) {
            data.forEach(item=>{
              item.label = item.systemName
              this.treeData[0].children.push(item)
            })
          }
        }).catch(error => {
          this.$message(error)
        })
      },
      //根据业务系统id，加载系统下所有菜单列表
      loadSystemMenuListWithBusinessSystemIdData(code){
        let postData={
          "businessSystemId": code
        }
        return new Promise(resolve => {
          API['loadSystemMenuListWithBusinessSystemId'](postData).then(response=>{
            const { data }=response;
            console.log(data)
            if (!data) {
              this.$message('数据读取失败')
              return
            }
            this.tableData = this.sort(data)
            resolve(data)
          }).catch(error => {
            this.$message(error)
          })
        })
      },
      sort(data){
        let result = []
        //循环遍历取出子集
        if(data.length) {
          //查询不是主菜单的子菜单,arr为子菜单，id为有子菜单的ids
          let arr=[],id=[]
          data.forEach(item=>{
            if (item.parentId!=0){
              arr.push(item)
              if (id.indexOf(item.parentId) == -1) {
                id.push(item.parentId)
              }
            }
          })
          //设置有子菜单的children
          id.forEach(d=>{
            data.forEach(item=>{
              if (d ==item.id) {
                item.children = []
              }
            })
          })
          //添加子菜单
          if (arr.length>0) {
            arr.forEach(a=>{
              data.forEach((item,index)=>{
                if (a.parentId == item.id) {
                  if(item.children) {
                    item.children.push(a)
                  }
                }
                // /*删除子菜单*/
                // if (item.parentId!=0) {
                //   data.splice(index,1)
                // }
              })
            })
            data.forEach((item,index)=>{
              /*删除子菜单 */
              if (item.parentId==0) {
                result.push(item)
              }
            })

          }
        }
        return result
      },
      //根据业务系统菜单加载所有菜单
      loadSystemMenuWithIdData(code){
        let postData={
          "id": code.id,  //业务系统菜单记录id
          "businessSystemId": code.businessSystemId    //业务系统id，用于加载系统下所有菜单，初始化界面上的下拉列表控件
        }
        return new Promise(resolve => {
          API['loadSystemMenuWithId'](postData).then(response=>{
            const { data }=response;
            if (!data) {
              this.$message('数据读取失败')
              return
            }
            if (data.menu) {
              this.saveData.menu = data.menu
            }
            if (data.menus) {
              this.saveData.menus = data.menus
            }
            resolve(data)
          }).catch(error => {
            this.$message(error)
          })
        })

      },
      //保存
      Save(){
        if ((Date.now() - this.onpresscTime) > 2000) {
          this.onpresscTime = Date.now()
          console.log(Date.now())
        }else{
          return
        }
        this.$refs.moduledialog.validate((valid) =>{
          if (valid && this.saveData.menu.menuIcon) {
            this.saveFlag = true
            this.form={brand_right:0}
            let postData = this.saveData.menu
            API['saveSystemMenu'](postData).then(response=>{
              const { message }=response;
              this.$message(message)
              let data = this.$refs.moduleManagementtree.getCheckedNodes()
              this.loadSystemMenuListWithBusinessSystemIdData(data[0].id)
              this.tableSelection = []
              this.dialogVisible = false
              this.iconselect=""
              this.saveFlag = false
            }).catch(error => {
              this.saveFlag = false
              this.$message(error)
            })
          } else {
            this.$message("信息未填写完整")
            return false;
          }
        })

      },
      iconSelect(){

        this.saveData.menu.menuIcon= this.iconselect
        this.icondialogVisible = false
      },//验证整数
      onlySortNumber(){
        // 先把非数字的都替换掉，除了数字和.
        let obj=this.saveData.menu.sort;
        obj=Number.parseInt(obj);
        this.saveData.menu.sort=obj;
      }
    },
    watch:{
      "dialogVisible"(){
        if (this.dialogVisible==false){
          this.$nextTick(() => {
            this.$refs.moduledialog.resetFields();
          })
        }

      }
    }
  }
</script>
<style>

</style>
<style scoped>

  .list{
    display: flex;flex-wrap: wrap;
    margin:5px 0px;
    justify-content: space-between;
    padding-left: 120px;
    text-align: left;
  }
  .list .item {
    font-size: 14px;
    font-weight: 400;
    line-height: 30px;
    /*width: 150px;*/
    height:30px;
    background-color: #efefef;
    padding:0 5px;
    border-radius:5px;
    overflow: hidden;
    margin-bottom: 10px;
    text-align: center;
  }
  .list .title{
    margin-right: 10px;
    float: left;
  }
  .list .delete{
    line-height: 30px;
    margin-left: 10px;
    color:red;
    float: right;
    cursor: pointer;
  }
  .wrapper{
    display: flex;
    flex-wrap: wrap;
    margin:5px 0px;
    justify-content: space-between;
    height:500px;
    overflow-y: auto;
  }

  .wrapper{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  .icon{
    flex:1;
    width:100px;
    height: 30px;
  }
</style>
